package com.apexedu.portal.util.umail.bjxml.xstream;

import com.apexedu.portal.util.umail.bjxml.xstream.converter.PojoMapConverter;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import java.util.Map;

/**
 * Created by luchen on 2015-12-23.
 */
public class BJXMLUtil
{
    public static Map<String, Object> xml2Map(String xml, String rootDomName)
    {
        Map result = null;
        XStream xstream = new XStream(new DomDriver());
        xstream.registerConverter(new PojoMapConverter());
        xstream.alias(rootDomName, Map.class);
        result = (Map)xstream.fromXML(xml);
        return result;
    }

    public static String map2Xml(Map<String, ? extends Object> map)
    {
        String result = null;
        XStream xstream = new XStream(new DomDriver());
        xstream.registerConverter(new PojoMapConverter());
        result = xstream.toXML(map);
        return result;
    }

    public static void main(String[] args) {
        String xml = "<?xml version='1.0' encoding='utf-8'?><result><stars><star><id>1</id><name>littleflower</name></star><star><id>2</id><name>littleyellow</name></star></stars>   <filename>cnlab</filename>   <ra>147.0</ra>   <dec>0.0</dec>   <plate>0.0</plate>   <mdj>0.0</mdj> </result> ";
        Map map = xml2Map(xml, "result");
        System.out.println(map);
        xml = map2Xml(map);
        System.out.println(xml);
        System.out.println(xml2Map(xml, "result"));
    }
}